package controller;

import common.StringUtil;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import model.User;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import service.UserService;

@Controller
@RequestMapping({ "/" })
public class LoginController {

	@Autowired
	private UserService userService;

	@SuppressWarnings({"rawtypes", "unchecked" })
	@RequestMapping(value = { "login" }, method=RequestMethod.POST)
	@ResponseBody
	public JSONObject login(HttpServletRequest request,
			@RequestParam(value = "username", required = false) String account,
			@RequestParam(value = "pwd", required = false) String pwd) {
		User user = new User();
		user.setAccount(account);
		user.setPassword(pwd);

		user = userService.findUser(user);

		Map map = new HashMap();

		if (!StringUtil.isEmpty(user)) {
			request.getSession().setAttribute("user", user);
			map.put("data", "success");
		} else {
			map.put("data", "error");
		}

		return JSONObject.fromObject(map);
	}
}